﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Data.Linq;
using NetDon.OA.Interface;
using SD.LLBLGen.Pro.ORMSupportClasses; 

namespace NetDon.OA.Business
{
    /// <summary>
    /// Manage the dynamic system configurations.
    /// </summary>
    public class ConfigurationService :CachableServiceBase<string>, IConfigurationService, IConfigurationManageService
    {
        public ConfigurationService()
            : base("Configuration")
        {
        }
        public virtual string GetConfiguration(ConfigurationData configurationData)
        {
            return GetData(configurationData);
        }

        /// <summary>
        /// Save all the configuration values.
        /// </summary>
        public virtual void SaveConfigurations(ConfigurationManageData configuration, ITransaction transaction)
        {
            foreach (string name in configuration.NameValueCollection)
            {
                ModifyData(new ConfigurationData{ AreaId = configuration.AreaId ,Name = name} , configuration.NameValueCollection[name], transaction);
            }
        }

        #region Overrides of CachableServiceBase<string>

        protected override string OnLoadData(object key, ITransaction transaction)
        {
            var configurationData = key as ConfigurationData;
            var metaData = new LinqMetaData(transaction);
            var query = from config in metaData.Configuration
                        where
                            config.Name == configurationData.Name && config.AreaId == configurationData.AreaId
                        select config.Value;
            var list = query.ToList();
            return list.Count > 0 ? list[0] : null;
        }

        protected override object GetDataKey(string data)
        {
            return null;
        }

        protected override bool OnModifyData(object key, string data, ITransaction transaction)
        {
            var configurationData = key as ConfigurationData;
            var collection = new ConfigurationCollection();
            transaction.Add(collection);
            collection.DeleteMulti(ConfigurationFields.Name == configurationData.Name & ConfigurationFields.AreaId == configurationData.AreaId);
            if (data != null)
            {
                var config = new ConfigurationEntity { Value = data, Name = configurationData.Name, AreaId = configurationData .AreaId};
                transaction.Add(config);
                config.Save();
            }
            return true;
        }
        #endregion

       
    }
}